package com.cspg.design.ui.schemeActivity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.cspg.design.CSPGApplication;
import com.cspg.design.R;
import com.cspg.design.adapter.Style;
import com.cspg.design.bean.UserInfo;
import com.cspg.design.bean.modelLibrary.TowerLibrary;
import com.cspg.design.bean.modelLibrary.TransformerLibrary;
import com.cspg.design.bean.modelLibrary.WireLibrary;
import com.cspg.design.bean.shemeBean.MyHighVoltageSchemeBean;
import com.cspg.design.dao.gen.DaoSession;
import com.cspg.design.dao.gen.MyHighVoltageSchemeBeanDao;
import com.cspg.design.dao.gen.TowerLibraryDao;
import com.cspg.design.dao.gen.WireLibraryDao;
import com.cspg.design.presenter.SchemePresenter;
import com.cspg.design.utils.ActionBarUtil;
import com.cspg.design.utils.StatusBarUtil;
import com.cspg.design.utils.Utils;
import com.cspg.design.widget.AlertListDialog;
import com.cspg.design.widget.Loading;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;

public class AerialSchemeActivity extends AppCompatActivity {


    private final List<String> wireModelList = new ArrayList<>();
    private final List<String> transformerModelList = new ArrayList<>();
    private final List<String> poleModelList = new ArrayList<>();
    private final List<WireLibrary> wireBeanList = new ArrayList<>();
    private final List<TowerLibrary> poleBeanList = new ArrayList<>();
    private final List<TransformerLibrary> transformerBeanList = new ArrayList<>();
    private WireLibrary selectWire;
    private DaoSession daoSession;
    private final List<TowerLibrary> choicePoles = new ArrayList<>();

    private ListView poleDialogListView = null;

    private SchemePresenter schemePresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_aerial_scheme);
        ActionBarUtil.setActionBar(this, R.string.voltage_10_Kv_aerial_scheme);
        StatusBarUtil.setStatusBarColor(this, R.color.colorPrimary);
        Utils.closeBoard(this);//隐藏键盘
        daoSession = ((CSPGApplication) getApplication()).getDaoSession();
        initData();

        EditText editText = findViewById(R.id.et_aerial_scheme_wire_model);
        editText.setOnClickListener(v -> new AlertListDialog.ListBuilder(AerialSchemeActivity.this)
                .setDividerColorRes(R.color.color_divider)
                .setDividerHeightRes(R.dimen.dp1)
                .setTitle("选择导线型号")
                .setIcon(R.drawable.ic_info)
                .setItems(wireModelList.toArray(new String[wireModelList.size()]), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        editText.setText(wireModelList.get(which));
                        selectWire = wireBeanList.get(which);
                    }
                }).create().show());
        EditText editText_trans = findViewById(R.id.et_aerial_scheme_transformer_model);
//        editText_trans.setOnClickListener(v -> new AlertListDialog.ListBuilder(AerialSchemeActivity.this)
//                .setDividerColorRes(R.color.color_divider)
//                .setDividerHeightRes(R.dimen.dp1)
//                .setNegativeButton("取消",null)
//                .setItems(transformerModelList.toArray(new String[transformerModelList.size()]), new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        editText_trans.setText(transformerModelList.get(which));
//                    }
//                }).create().show());
        editText_trans.setOnClickListener(v->{
            showTransformAlertDialog();
        });
        Button btn_design_model = findViewById(R.id.btn_aerial_scheme_design_model);
        btn_design_model.setOnClickListener(v -> {
            showPoleAlertDialog();
        });

        Button btn_save = findViewById(R.id.btn_aerial_scheme_save);
        btn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Utils.closeBoard(AerialSchemeActivity.this);//隐藏键盘
                new Thread(){
                    @Override
                    public void run() {
                        saveData();
                    }
                }.start();
            }
        });
        schemePresenter = new SchemePresenter(this,null,null);
    }

    private void initData() {

        daoSession.getWireLibraryDao().queryBuilder().where(WireLibraryDao.Properties.VoltageLevel.eq("10kV"))
                .rx().list().observeOn(AndroidSchedulers.mainThread()).subscribe(
                wireLibraries -> {
                    for (int i = 0; i < wireLibraries.size(); i++) {
                        wireModelList.add(wireLibraries.get(i).getWireModel());
                        wireBeanList.add(wireLibraries.get(i));
                    }
                }
        );

        daoSession.getTransformerLibraryDao().queryBuilder().rx().list().observeOn(AndroidSchedulers.mainThread()).subscribe(
                transformerLibraries -> {
                    for (int i = 0; i < transformerLibraries.size(); i++) {
                        transformerModelList.add(transformerLibraries.get(i).getTransformerModel());
                        transformerBeanList.add(transformerLibraries.get(i));
                    }
                }
        );


        daoSession.getTowerLibraryDao().queryBuilder().rx().list().observeOn(AndroidSchedulers.mainThread()).subscribe(
                towerLibraries -> {
                    poleBeanList.addAll(towerLibraries);
                }
        );
    }

    private void showPoleAlertDialog() {
        Utils.closeBoard(this);
        List<TowerLibrary> towerLibraryList = daoSession.getTowerLibraryDao().queryBuilder()
                .where(TowerLibraryDao.Properties.VoltageLevel.like("%10%"))
                .list();
        List<TowerLibrary> filterTowerLibraryList = new ArrayList<>();
        List<String> towerList = new ArrayList<>();
        String[] towerNames;
        boolean[] isChoice;
        if (selectWire == null)
        {
            towerNames = new String[towerLibraryList.size()];
            isChoice = new boolean[towerLibraryList.size()];
            for (int i = 0; i < towerLibraryList.size(); i++) {
                TowerLibrary towerLibrary = towerLibraryList.get(i);
                towerNames[i] = towerLibrary.getPoleModel();
                filterTowerLibraryList.add(towerLibrary);
                isChoice[i] = false;
            }
        }
        else
        {
            int cross_section = Integer.parseInt(selectWire.getWireCrossSection());
            for (int i = 0; i < towerLibraryList.size(); i++) {
                TowerLibrary towerLibrary = towerLibraryList.get(i);
                int maxCrossSection = Integer.parseInt(towerLibrary.getMaxWireCrossSection());
                int minCrossSection = Integer.parseInt(towerLibrary.getMiniWireCrossSection());
                if (cross_section >= minCrossSection && cross_section <= maxCrossSection && towerLibrary.getWireQuality().equals(selectWire.getWireQuality()))
                {
                    towerList.add(towerLibrary.getPoleModel());
                    filterTowerLibraryList.add(towerLibrary);
                }
            }
            towerNames = towerList.toArray(new String[towerList.size()]);
            isChoice = new boolean[towerList.size()];
            for(int i=0;i<towerList.size();i++)
            {
                isChoice[i] = false;
            }
        }
        choicePoles.clear();
        AlertDialog alertDialog = new AlertListDialog.ListBuilder(this).
                setDividerColorRes(R.color.color_divider)
                .setDividerHeightRes(R.dimen.dp1)
                .setTitle("选择杆塔型号")
                .setIcon(R.drawable.ic_info)
                .setMultiChoiceItems(towerNames, isChoice, (dialog, which, isChecked) -> {
            if (isChecked) {
                choicePoles.add(filterTowerLibraryList.get(which));
            }
        }).setNeutralButton("全选",null).setCancelable(true).setPositiveButton("确定",(dialog, v)->{
            Button btn_design_model = findViewById(R.id.btn_aerial_scheme_design_model);
            if(choicePoles.size() != 0)
            {
                btn_design_model.setText("修改");
            }
            dialog.dismiss();
        }).setNegativeButton("取消",(dialog,which)->{
            choicePoles.clear();
            dialog.dismiss();
        }).create();
        poleDialogListView = alertDialog.getListView();
        alertDialog.show();
        Button btn = alertDialog.getButton(AlertDialog.BUTTON_NEUTRAL);
        if (btn != null)
        {
            btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    for (int i = 0; i< filterTowerLibraryList.size();i++)
                    {
                        poleDialogListView.setItemChecked(i,true);
                        choicePoles.add(filterTowerLibraryList.get(i));
                        isChoice[i] = true;
                    }
                }
            });
        }
    }

    public void showTransformAlertDialog()
    {
        ListView listView = new ListView(this);
        View view = LayoutInflater.from(this).inflate(R.layout.tranformer_dialog_header,null,false);
        listView.addHeaderView(view);
        ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
        for (int i = 0 ; i < transformerBeanList.size();i++)
        {
            TransformerLibrary transformerLibrary = transformerBeanList.get(i);
            HashMap<String,String> map = new HashMap<>();
            map.put("pole", transformerLibrary.getPoleModel());
            map.put("transformer", transformerLibrary.getTransformerModel());
            map.put("capacity", transformerLibrary.getCapacity());
            dataList.add(map);
        }

        SimpleAdapter adapter = new SimpleAdapter(this, dataList, R.layout.transformer_dialog_item,
                new String[]{"pole", "transformer", "capacity"},
                new int[]{R.id.transformer_dialog_pole, R.id.transformer_dialog_trans, R.id.transformer_dialog_capacity}
        );
        listView.setAdapter(adapter);
        androidx.appcompat.app.AlertDialog dialog = new  androidx.appcompat.app.AlertDialog.Builder(this)
                .setView(listView)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).create();
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TransformerLibrary transformerLibrary = transformerBeanList.get(position - 1);
                EditText et_transformer_model = findViewById(R.id.et_aerial_scheme_transformer_model);
                et_transformer_model.setText(transformerLibrary.getPoleModel());
                dialog.dismiss();
            }
        });
        dialog.show();


    }

    private void saveData() {

        String tip = "";

        EditText et_wire_model = findViewById(R.id.et_aerial_scheme_wire_model);
        EditText et_transformer_model = findViewById(R.id.et_aerial_scheme_transformer_model);
        EditText et_flat_ground = findViewById(R.id.et_aerial_flat_ground);
        EditText et_hilly_area = findViewById(R.id.et_aerial_hilly_area); /*山地*/
//        EditText et_high_mountain = findViewById(R.id.et_aerial_high_mount); //高山</string>
        EditText et_hills = findViewById(R.id.et_aerial_hills); //丘陵</string>
        EditText et_common_soil = findViewById(R.id.et_aerial_common_soil); //普通土</string>
        EditText et_hard_soil = findViewById(R.id.et_aerial_hard_soil); //坚土</string>
        EditText et_loose_sandstone = findViewById(R.id.et_aerial_loose_sandstone); //松砂石</string>
        EditText et_mud_puddle = findViewById(R.id.et_aerial_mud_puddle); //泥水坑</string>
        EditText et_rock = findViewById(R.id.et_aerial_rock); //岩石</string>
        if (!Utils.isInteger(et_flat_ground.getText().toString())) {
           tip = "平地请输入数字";
        }
//        else if (!Utils.isInteger(et_high_mountain.getText().toString())) {
//            tip = "高山请输入数字";
//        }
        else if (!Utils.isInteger(et_hilly_area.getText().toString())) {
            tip = "山地请输入数字";
        }
        else if (!Utils.isInteger(
                et_hills.getText().toString())) {
            tip =  "丘陵请输入数字";
        }
        if (!tip.isEmpty())
        {
            final String msg  = tip;
            Handler handler = new Handler(Looper.getMainLooper());
            handler.post(() -> {
                Toast.makeText(AerialSchemeActivity.this, msg, Toast.LENGTH_LONG).show();
            });
            return;
        }
        int flatGround = Integer.parseInt(et_flat_ground.getText().toString());
        int hillyArea = Integer.parseInt(et_hilly_area.getText().toString());
//        int highMountain = Integer.parseInt(et_high_mountain.getText().toString());
        int hills = Integer.parseInt(et_hills.getText().toString());
        if ((flatGround + hillyArea  + hills) > 100) {
            tip =  "各种地形的和不能大于100";

        }
        else if ((flatGround + hillyArea  + hills) < 100)
        {
            tip =  "各种地形的和不能小于100";

        }
        else if (!Utils.isInteger(
                et_common_soil.getText().toString())){
            tip =  "普通土请输入数字";

        }
        else if (!Utils.isInteger(
                et_hard_soil.getText().toString())) {
            tip =  "坚土请输入数字";

        }
        else if (!Utils.isInteger(
        et_loose_sandstone.getText().toString())) {
            tip =  "松砂石请输入数字";

        }
        else if (!Utils.isInteger( et_rock.getText().toString())) {
            tip =  "岩石请输入数字";

        }
        else if (!Utils.isInteger(et_mud_puddle.getText().toString())) {
            tip =  "泥水坑请输入数字";

        }
        if (!tip.isEmpty())
        {
            final String msg  = tip;
            Handler handler = new Handler(Looper.getMainLooper());
            handler.post(() -> {
                Toast.makeText(AerialSchemeActivity.this, msg, Toast.LENGTH_LONG).show();
                Loading.getIns().target(AerialSchemeActivity.this).show(Style.CANCEL);
            });
            return;
        }
        int loosenSandstone = Integer.parseInt(et_loose_sandstone.getText().toString());
        int commonSoil = Integer.parseInt(et_common_soil.getText().toString());
        int hardSoil = Integer.parseInt(et_hard_soil.getText().toString());
        int mudPuddle = Integer.parseInt(et_mud_puddle.getText().toString());
        int rock = Integer.parseInt(et_rock.getText().toString());
        if ((loosenSandstone + commonSoil + hardSoil + mudPuddle + rock) > 100) {
            tip =  "各种地质的和不能大于100";

        }
        else if ((loosenSandstone + commonSoil + hardSoil + mudPuddle + rock) < 100) {
            tip =  "各种地质的和不能小于100";

        }
        else if (et_wire_model.getText().toString().trim().equals("")) {
            tip =  "请选择导线型号";

        }
        else if (choicePoles.size() == 0) {
            tip =  "请在典型设计模块中添加数据";

        }
        if (!tip.isEmpty())
        {
            final String msg  = tip;
            Handler handler = new Handler(Looper.getMainLooper());
            handler.post(() -> {
                Toast.makeText(AerialSchemeActivity.this, msg, Toast.LENGTH_LONG).show();
                Loading.getIns().target(AerialSchemeActivity.this).show(Style.CANCEL);
            });
            return;
        }
        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(() -> {
            EditText schemeName = new EditText(this);
            schemeName.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
            new AlertDialog.Builder(this)
                    .setTitle("请输入方案名称")
                    .setIcon(R.drawable.ic_info)
                    .setView(schemeName)
                    .setCancelable(true)
                    .setOnCancelListener(new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            dialog.dismiss();
                            Loading.getIns().target(AerialSchemeActivity.this).show(Style.CANCEL);
                        }
                    })
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Utils.closeBoard(AerialSchemeActivity.this);
                            if (schemeName.getText().toString().trim().equals("")) {
                                Toast.makeText(AerialSchemeActivity.this, "请输入方案名称", Toast.LENGTH_LONG).show();
                                return;
                            }
                            String poleModels = "";
                            for (int i = 0; i < choicePoles.size(); i++) {
                                if ((i+1)==choicePoles.size())
                                {
                                    poleModels += choicePoles.get(i).getPoleModel() ;
                                }
                                else
                                {
                                    poleModels += choicePoles.get(i).getPoleModel()+ "&" ;
                                }                            }
                            MyHighVoltageSchemeBean myHighVoltageSchemeBean = new MyHighVoltageSchemeBean(
                                    null, Utils.uuid() ,schemeName.getText().toString(), "10KV",
                                    et_wire_model.getText().toString(),
                                    et_transformer_model.getText().toString(),
                                    flatGround + "", hillyArea + "", 0 + "", hills + "",
                                    commonSoil + "", hardSoil + "", loosenSandstone + "", mudPuddle + "", rock + "",
                                    poleModels, UserInfo.getInstance().userName
                            );
                            List<MyHighVoltageSchemeBean> myHighVoltageSchemeBeans =  daoSession
                                    .getMyHighVoltageSchemeBeanDao().queryBuilder()
                                    .where(MyHighVoltageSchemeBeanDao.Properties.SchemeName.eq(myHighVoltageSchemeBean.getSchemeName()))
                                    .list();
                                if (myHighVoltageSchemeBeans.size() ==0)
                                {
                                    schemePresenter.addHighVoltageScheme(myHighVoltageSchemeBean);
                                }
                                else
                                {
                                    Utils.closeBoard(AerialSchemeActivity.this);
                                    Toast.makeText(AerialSchemeActivity.this,"此名称已经被占用，请更换一个方案名",Toast.LENGTH_LONG).show();
                                }
                        }
                    }).create().show();
        });
    }

    /**
     * 点击空白区域隐藏键盘.
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (AerialSchemeActivity.this.getCurrentFocus() != null) {
                if (AerialSchemeActivity.this.getCurrentFocus().getWindowToken() != null) {
                    imm.hideSoftInputFromWindow(AerialSchemeActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
        }
        return super.onTouchEvent(event);
    }

}